# Maintainer: Alexey Pavlov <alexpux@gmail.com>

_realname=cfitsio
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.3.0
pkgrel=1
epoch=1
pkgdesc="A library of C and Fortran subroutines for reading and writing data files in FITS (Flexible Image Transport System) data format (mingw-w64)"
arch=('any')
mingw_arch=('mingw32' 'mingw64' 'ucrt64' 'clang64' 'clang32' 'clangarm64')
url="https://heasarc.gsfc.nasa.gov/fitsio/"
license=("custom")
makedepends=("${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-pkg-config")
depends=("${MINGW_PACKAGE_PREFIX}-gcc-libs"
         "${MINGW_PACKAGE_PREFIX}-curl"
         "${MINGW_PACKAGE_PREFIX}-zlib")
source=("https://heasarc.gsfc.nasa.gov/FTP/software/fitsio/c/${_realname}-${pkgver}.tar.gz")
sha256sums=('fdadc01d09cf9f54253802c5ec87eb10de51ce4130411415ae88c30940621b8b')

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  if [[ ${CARCH} != aarch64 ]]; then
    extra_config+=("-DUSE_SSE2=ON")
  fi

  msg "Build static library"
  [[ -d ${srcdir}/static-${MSYSTEM} ]] && rm -rf ${srcdir}/static-${MSYSTEM}
  mkdir ${srcdir}/static-${MSYSTEM} && cd "${srcdir}/static-${MSYSTEM}"

  CFLAGS+=" -D_LARGEFILE_SOURCE=ON -D_FILE_OFFSET_BITS=64" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX" \
    ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    ${extra_config[@]} \
    -DBUILD_SHARED_LIBS=OFF \
    -DUSE_PTHREADS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .

  msg "Build shared library"
  [[ -d ${srcdir}/shared-${MSYSTEM} ]] && rm -rf ${srcdir}/shared-${MSYSTEM}
  mkdir ${srcdir}/shared-${MSYSTEM} && cd "${srcdir}/shared-${MSYSTEM}"

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX" \
  CFLAGS+=" -D_LARGEFILE_SOURCE=ON -D_FILE_OFFSET_BITS=64" \
    ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DCMAKE_SHARED_LIBRARY_NAME_WITH_VERSION=ON \
    ${extra_config[@]} \
    -DBUILD_SHARED_LIBS=ON \
    -DUSE_PTHREADS=ON \
    -DUTILS=ON \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake --build .
}

package() {
  cd "${srcdir}/static-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  cd "${srcdir}/shared-${MSYSTEM}"
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake --install .

  install -Dm644 ${srcdir}/${_realname}-${pkgver}/License.txt "${pkgdir}${MINGW_PREFIX}"/share/licenses/${_realname}/LICENSE
}
